from ftplib import FTP
import datetime
import sys
import smtplib
from email.mime.text import MIMEText

def GetWeekDayStatus(SomeDate):
    if SomeDate.weekday() == 5 or SomeDate.weekday() == 6:
        return False
    else:
        return True
    

def GetDateListFromFTPFileNames():
    ftp = FTP('192.168.100.8', 'TechnologyTruckInspection', 'readonlyfortruckinspection')
    DirectoryList = []
    ftp.retrlines('MLSD', DirectoryList.append)
    ftp.close()
    Return=[]
    for i in DirectoryList:
        try:
            Step1 = i.split(';')
            Step2 = Step1[3][-14:-4]
            SomeDate = datetime.datetime.strptime(Step2, '%Y-%m-%d').date()
            Return.append(SomeDate)
        except:
            pass
    return Return

def GetInspectionStatus(InspectionDate):
    Today = datetime.datetime.now().date()
    DaysThisWeek=[]
    DateToEvaluate = Today
    #get a list of days from today back to Monday, including Monday
    #Monday == 0, Tuesday == 1, etc.  Sunday == 6.  Value loops each week.
    while DateToEvaluate.weekday() < 6:
        DaysThisWeek.append(DateToEvaluate)
        DateToEvaluate -= datetime.timedelta(days=1)
    if InspectionDate in DaysThisWeek:
        return True
    else:
        return False

def SendMail(Success, LastDate):
    if Success:
        return
    Body='Last Truck Inspection: ' + str(LastDate)
    Message=MIMEText(Body)
    Message['Subject']='Automated ALERT: No Truck Inspection Found'
    Message['From']='COOPIP@tce.coop'
    Message['To']='technology@tce.coop'
    Sender=smtplib.SMTP('192.168.100.8')
    Sender.sendmail('arbitrary@tce.coop', ['technology@tce.coop'], Message.as_string())
    Sender.quit()
    print 'Email Sent'
    
    

Today = datetime.datetime.now()
TodayIsWeekday = GetWeekDayStatus(Today)
if not TodayIsWeekday:
    sys.exit(0)

DateList = GetDateListFromFTPFileNames()
if not DateList:
    sys.exit(0)
DateList.sort()
MostRecent = DateList[-1]

InspectionCompleted = GetInspectionStatus(MostRecent)
SendMail(InspectionCompleted, MostRecent)
sys.exit(0)
